<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Model\GroupList;
use App\Model\UserModel;
use App\Model\GroupListLog;
use App\Model\GroupListCite;
use App\Model\GroupListOrder;
use App\Model\UserWalletModel;
use Illuminate\Support\Facades\DB;


class Group extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'group';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = '拼团商品到期';//够30天就清空业绩

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	public function handle()
	{
		DB::beginTransaction();
		try{
			//拼团商品到期之后，将商品的状态更改为已过期，开关关闭，第几轮+1 ，计算到期的订单
            $list = GroupList::where('end','<=',date('Y-m-d H:i:s'))->where('switch',1)->get();
			foreach($list as $k=>$v){
				$no_order = GroupListOrder::where('gid',$v['id'])->where('curcle',$v['curcle'])->get();
				//商品信息
				$good = GroupList::where('id',$v['id'])->first();
				//增加拼团历史记录
				GroupListCite::create([
					'gid' => $good['id'],
					'gname' => $good['name'],
					'gpic' => $good['picname'],
					'cost' => $good['cost'],
					'sell' => $good['sell'],
					'charge' => $good['charge'],
					'shares' => $good['shares'],
					'start' => $good['start'],
					'end' => $good['end'],
					'nums' => $good['nums'],
					'site' => 0,
					'curcle' => $good['curcle'],
					'attr' => $good['attr'],
					'state' => 2,
				]);

				if(count($no_order) > 0){
					foreach($no_order as $key=>$val){
						//商品过期，未拼团成功的商品   本金返还
						//用户信息
						$user = UserModel::where('id',$val['uid'])->first();
						if($val['paytype'] == 1 || $val['paytype'] == 2){
							UserWalletModel::handleAccount($user['id'],$val['sum'],'+','拼团失败，返还本金',$val['paytype'],18);
						}
						
						//更改拼团记录的状态为4
						GroupListLog::where('oid',$val['id'])->update(['state'=>4]);
						//更改拼团订单的状态为完成
						GroupListOrder::where('id',$val['id'])->update(['state'=>1]);
						//更改商品的状态
						GroupList::where('id',$val['gid'])->update(['switch'=>2]);
						// GroupList::where('id',$val['gid'])->increment('curcle');
					}
				}else{
					GroupList::where('id',$v['id'])->update(['switch'=>2]);
				}
			}

			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
        }
        return ['code'=>1,'msg'=>"操作完成"];
	}
}